package levelrewind.android.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import levelrewind.android.app.adapter.FriendsAdapter;
import levelrewind.android.app.adapter.GameListAdapter;
import levelrewind.android.app.adapter.HighScoreAdapter;
import levelrewind.android.app.adapter.LatestPlayerAdapter;
import levelrewind.android.app.adapter.PersonListAdapter;
import levelrewind.android.app.model.LineChart;
import levelrewind.android.app.model.PictureHandler;
import levelrewind.android.app.model.RestDataHandler;
import levelrewind.android.app.model.Util;
import levelrewind.android.app.model.Util.Emotion;
import levelrewind.android.app.vo.Battle;
import levelrewind.android.app.vo.Category;
import levelrewind.android.app.vo.Game;
import levelrewind.android.app.vo.HighScore;
import levelrewind.android.app.vo.LatestPlayer;
import levelrewind.android.app.vo.Person;
import levelrewind.android.app.vo.PersonPlace;
import levelrewind.android.app.vo.PersonScore;
import levelrewind.android.app.vo.User;
import levelrewind.android.app.vo.UserScore;

import org.achartengine.GraphicalView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.facebook.Session;
import com.greystripe.sdk.GSMobileBannerAdView;

public class MainActivity extends FragmentActivity {
	//XML variables
	private ViewSwitcher personDataViewSwitcher;
	private LinearLayout cat_scroll;
	private ExpandableListView expList;
	private ListView scoreView;
	private Button btnPlay;
	private Button btnPlayMain;
	private Button btnLatest; 
	private Button btnHigh; 
	private Button btnFriends;
	private View scoreHeader;
	//private TextView txtUserName;
	//private ImageView imgUserView;
	
	// Class variables
	private Person curPerson = null;
	private RestDataHandler dataHandler;
	private Category[] categories; 
	private Category curCategory;
	private PersonPlace personPlace;
	private Button[] catButtons;
	private GSMobileBannerAdView adBanner;
	
	//Value variables
	private int listHeight = 0;
	private int curGroupPosition = 0;
	public int playCtrl = 0;

	//Constant values
	public final int SCORE_LIST = 0;
	public final int GAME_LIST = 1;
	private final int NEW_GAME = 0;
//	private final int POST_GAME = 1;
		
	public void onCreate(Bundle savedInstanceState) {
		
        try
        {
        	super.onCreate(savedInstanceState);	
        	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        	setContentView(R.layout.activity_main);
        	
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                                    
            // initial view
        	findViewsByID();
        	
        	// Get categories data and set to menu
        	categories = dataHandler.getCategoriesFromDevice();
        	createCategoryBar();
        	catButtons[0].setTextColor(getResources().getColor(R.color.blueTextColor));
        	        	
        	// Get Battles and set it to battle's banner
    		new GetBattlesTask().execute();
        	
        	//String deviceId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
            //Log.i("Device ID", deviceId+"");
            
        	//Add banner
        	adBanner = (GSMobileBannerAdView)this.findViewById(R.id.gsBanner);
        	adBanner.refresh();
        }
        
        catch (Exception e) 
        {
        	e.printStackTrace();
			System.out.println("Error +++ " + e.getMessage());
		}
    }
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		
		// Refresh battle in banner
		new GetBattlesTask().execute();
		
		// Refresh Login title
//		displayUserLoggedInStatus();
	}
	
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    	super.onActivityResult(requestCode, resultCode, data);
    	//facebookHandler.getFacebook().authorizeCallback(1, resultCode, data);
    	Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);

    	if (requestCode == NEW_GAME) { 
    	 
    	     if(resultCode == RESULT_OK){ 
    	    	 updateTotalScore();
    	     }
    	     else if (resultCode == RESULT_CANCELED) { } 
    	 
    	}  
    }
	 
//	private void loginControl() {
//		//TODO: logout
////		if (FacebookHandler.isLoggedIn)facebookHandler.logout();
////    	else facebookHandler.login();
//		collapseList();
//	}
	
//	@Override
//	 public boolean onPrepareOptionsMenu(Menu menu) {
//		MenuItem item = menu.findItem(R.id.fb_logout);
//		// Get facebook session
//		Session session = Session.getActiveSession();
//		item.setTitle(session.isOpened() ? R.string.fb_logout : R.string.fb_login );
//		return true;
//	 }
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
//        MenuItem item = menu.findItem(R.id.fb_logout);
//        // Get facebook session
//        Session session = Session.getActiveSession();
//		item.setTitle(session.isOpened() ? R.string.fb_logout : R.string.fb_login );
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
//            case R.id.fb_logout:     
//            	loginControl();
//            	break;
            case R.id.update_data:
            	startActivity(new Intent(MainActivity.this, AppStartActivity.class));
            	break;	
        }
        return true;
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        	
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.quit_header);
            builder.setMessage(R.string.quit_msg);
        	builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
    			
    			@Override
    			public void onClick(DialogInterface dialog, int which) {
    				finish();
    			}
    		});
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
    			
    			@Override
    			public void onClick(DialogInterface dialog, int which) {
    				dialog.dismiss();
    			}
    		});
            
            builder.create().show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @SuppressWarnings("unused")
	private void collapseList() {
    	expList.collapseGroup(curGroupPosition);
    }
   
    // Initialize Category Scrollbar and ExpandableListView
    private void createCategoryBar()
    {
    	catButtons = new Button[categories.length];
    	for (int i = 0; i < categories.length; i++)
    	{
    		final int curIndex = i;
    		Button b = new Button(getApplicationContext());
    		b.setText(categories[i].getName());
    		b.setTypeface(Util.customFont(this),Typeface.NORMAL);
    		b.setTextColor(Color.WHITE);
    		b.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_box));
//    		b.setLayoutParams(new LinearLayout.LayoutParams(100, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));
    		
    		// set text size by screen size
    		if ((getResources().getConfiguration().screenLayout & 
    			    Configuration.SCREENLAYOUT_SIZE_MASK) == 
    			        Configuration.SCREENLAYOUT_SIZE_NORMAL) {
    			b.setTextSize(22);

    		} else if ((getResources().getConfiguration().screenLayout & 
    			    Configuration.SCREENLAYOUT_SIZE_MASK) == 
    			        Configuration.SCREENLAYOUT_SIZE_LARGE) {
    			b.setTextSize(32);

    		} else if ((getResources().getConfiguration().screenLayout & 
    			    Configuration.SCREENLAYOUT_SIZE_MASK) == 
    			        Configuration.SCREENLAYOUT_SIZE_XLARGE) {
    			b.setTextSize(42);

    		}

    		if (i == 0) {curCategory = categories[curIndex];}
    		
    		final Person[] person = dataHandler.getPersonsFromDevice(categories[i].getId());

    		b.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				curCategory = categories[curIndex];
    				changeCategory(curIndex);
    				setExpandableListAdapter(person);
    			}
    		});
    		catButtons[i] = b;
    		cat_scroll.addView(b, 155, LinearLayout.LayoutParams.WRAP_CONTENT);
		}
    	if (curCategory != null) {
    		setExpandableListAdapter(dataHandler.getPersonsFromDevice(curCategory.getId()));
		}
    }
    
    // Change layout for selected category
    private void changeCategory(int number)
    {
    	for (int i = 0; i < catButtons.length; i++) {
			catButtons[i].setTextColor(Color.WHITE);
		}
    	catButtons[number].setTextColor(getResources().getColor(R.color.blueTextColor));
    }
    
    private void setExpandableListAdapter(Person[] persons)
    {
    	expList = (ExpandableListView) this.findViewById(R.id.listView);
    	
    	expList.setAdapter(new PersonListAdapter(this, persons));
    	
    	//Add banner, put list between line and banner
    	RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    	params.addRule(RelativeLayout.BELOW, R.id.line2);
    	params.addRule(RelativeLayout.ABOVE, R.id.gsBanner);
    	expList.setLayoutParams(params);
    	
    	expList.setOnChildClickListener(new OnChildClickListener() {
    		@Override
    		public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				return true;
			}
		});
    	
    	expList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
			
			@Override
			public void onGroupCollapse(int groupPosition) {
				try {
		    		setDefaultSubList();
				} catch (Exception e)
				{
					
				}
				
			}
		});
    	
    	expList.setOnGroupExpandListener(new OnGroupExpandListener() {
			
			@Override
			public void onGroupExpand(int groupPosition) {
				myOnGroupExpand(groupPosition);
			}
		});
    	
    }
    
    // Find view and make local variables by ID
    private void findViewsByID()
    {
    	dataHandler = new RestDataHandler(MainActivity.this);
    	cat_scroll = (LinearLayout) this.findViewById(R.id.cat_scroll);
    	scoreView = (ListView) this.findViewById(R.id.statsScores);
    }
    
    private void setBattleBanner(Battle[] battles) {
    	
    	LinearLayout bannerLayout = (LinearLayout)this.findViewById(R.id.bannerLayout);
    	if (battles != null && battles.length != 0) {
    		bannerLayout.setVisibility(View.VISIBLE);
	    	TextView slogan = (TextView)findViewById(R.id.banner_slogan);
	    	TextView txtVS = (TextView)findViewById(R.id.banner_vs);
	    	ImageView per1Pic = (ImageView)findViewById(R.id.banner_person1_pic);
	    	ImageView per2Pic = (ImageView)findViewById(R.id.banner_person2_pic);
	    	
	    	txtVS.setText(getString(R.string.vs));
	    	
	    	slogan.setTypeface(Util.customFont(this));
	    	txtVS.setTypeface(Util.customFont(this));
	    	
	    	
	    	// Random en battle
	    	Random rand = new Random();
	    	Battle battle = battles[rand.nextInt(battles.length)];
	    	
	    	slogan.setText(battle.getSlogan());
	    	PictureHandler.viewImageFromDevice(this, battle.getPersons()[0].getPerson(), Emotion.NORMAL, per1Pic);
	    	PictureHandler.viewImageFromDevice(this, battle.getPersons()[1].getPerson(), Emotion.NORMAL, per2Pic);
    	} 
    	else {
    		bannerLayout.setVisibility(View.GONE);
    	}
    }
    
    public void  onContentChanged  () {
    	System.out.println("onContentChanged");
	    super.onContentChanged();	      
    }

    private void setDefaultSubList() {
    	btnLatest = (Button)findViewById(R.id.btnLatestScores);
    	btnHigh = (Button)findViewById(R.id.btnHighScores);
    	btnFriends = (Button)findViewById(R.id.btnFriendScores);
    	btnLatest.setTypeface(Util.customFont(this), Typeface.NORMAL);
    	btnHigh.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnFriends.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnLatest.setTextColor(getResources().getColor(R.color.blueTextColor));
    	btnHigh.setTextColor(Color.WHITE);
    	btnFriends.setTextColor(Color.WHITE);
    }
    
    // This function is called on expansion of the group
    private void  myOnGroupExpand  (int groupPosition) 
    {
    	try
    	{
    		if (playCtrl == GAME_LIST) 
        	{
        		playCtrl = SCORE_LIST; 
        		personDataViewSwitcher.showNext();
    		}
    		
    		expList.setSelectionFromTop(groupPosition, 0);
    		
    		int count = expList.getExpandableListAdapter().getGroupCount();
    		for (int i = 0; i < count; i++) {
				if (i != groupPosition) {
					expList.collapseGroup(i);
				}
			}
    		ExpandableListAdapter mAdapter = expList.getExpandableListAdapter();
			curPerson = (Person) mAdapter.getGroup(groupPosition);
			curGroupPosition = groupPosition;

			if (!Util.isOnline(this)) 
	    	{
	    		setEmptyListAdapter();
			}
			
    	}
    	catch(Exception e) {
    		e.printStackTrace();
    	}
    }

    // Set No Data-adapter to scoreView if isOnline == false
    private void setEmptyListAdapter()
    {
    	scoreView = (ListView) findViewById(R.id.statsScores);
    	String[] values = new String[] { "Connection failed...\nNot able to retrieve data from server"};

    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);

    	scoreView.setAdapter(adapter);
    	adapter.notifyDataSetChanged();
    }
    
//    public void loginClicked(View v){
//		if (Util.isOnline(this)) {
//			loginControl();
//		}
//		else {
//			//TODO: retry login dialog
//		}
//		
//	}
	
	public void battleListClicked(View v)
    {
    	if (Util.isOnline(this)){
    		Intent myIntent = new Intent(MainActivity.this, BattleListActivity.class);
        	startActivity(myIntent);
    	}
    	else {
    		//TODO: retry login dialog
    	}
    	
    }
	
    // Called when Play Button clicked in ExpListView
    public void playBtn(View v)
    {
    	personDataViewSwitcher = (ViewSwitcher) findViewById(R.id.personDataViewSwitcher);
    	personDataViewSwitcher.showNext();
    	
    	btnPlay = (Button) findViewById(R.id.btnPlay);
    	btnPlayMain = (Button) findViewById(R.id.btnPlayMain);
    	if (playCtrl == SCORE_LIST)
    	{
    		btnPlay.setVisibility(View.VISIBLE);
    		btnPlayMain.setVisibility(View.GONE);
    		btnPlay.setText(R.string.list_back);
    		playCtrl = GAME_LIST;
    		getGamesToList();
    	}
    	else
    	{
    		btnPlay.setVisibility(View.GONE);
    		btnPlayMain.setVisibility(View.VISIBLE);
    		btnPlay.setText(R.string.play); 
    		playCtrl = SCORE_LIST;
    		
    		if (Util.isOnline(this)) {
	    		new GetLatestPlayerTask().execute(curPerson.getId());
	    		
	    		// Update score only when a game is played
	    		if (personPlace != null) {
	    			new GetScoresTask().execute(curPerson.getId());
	    		}
	    		
	    		setDefaultSubList();
    		}
    		
    	}
    	
    }

    // Events called when Latest Scores, Highscores og Friends' scores are clicked
    public void latestScores(View v)
    {
    	btnLatest = (Button)findViewById(R.id.btnLatestScores);
    	btnHigh = (Button)findViewById(R.id.btnHighScores);
    	btnFriends = (Button)findViewById(R.id.btnFriendScores);
    	btnLatest.setTypeface(Util.customFont(this), Typeface.NORMAL);
    	btnHigh.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnFriends.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnLatest.setTextColor(getResources().getColor(R.color.blueTextColor));
    	btnHigh.setTextColor(Color.WHITE);
    	btnFriends.setTextColor(Color.WHITE);
    	
    	if (Util.isOnline(this)) new GetLatestPlayerTask().execute(curPerson.getId());
    	else setEmptyListAdapter();
    }
    
    public void highScores(View v)
    {
    	btnLatest = (Button)findViewById(R.id.btnLatestScores);
    	btnHigh = (Button)findViewById(R.id.btnHighScores);
    	btnFriends = (Button)findViewById(R.id.btnFriendScores);
    	btnLatest.setTypeface(Util.customFont(this), Typeface.NORMAL);
    	btnHigh.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnFriends.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnHigh.setTextColor(getResources().getColor(R.color.blueTextColor));
    	btnLatest.setTextColor(Color.WHITE);
    	btnFriends.setTextColor(Color.WHITE);
    	
    	if (Util.isOnline(this)) {
    		new GetHighScoreTask().execute(curPerson.getId());
    	}
    	else setEmptyListAdapter();
    }
    
    public void friendScores(View v)
    {
    	btnLatest = (Button)findViewById(R.id.btnLatestScores);
    	btnHigh = (Button)findViewById(R.id.btnHighScores);
    	btnFriends = (Button)findViewById(R.id.btnFriendScores);
    	btnLatest.setTypeface(Util.customFont(this), Typeface.NORMAL);
    	btnHigh.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnFriends.setTypeface(Util.customFont(this),Typeface.NORMAL);
    	btnFriends.setTextColor(getResources().getColor(R.color.blueTextColor));
    	btnLatest.setTextColor(Color.WHITE);
    	btnHigh.setTextColor(Color.WHITE);
    	
    	// Check if user is online and logged in with facebook
    	Session session = Session.getActiveSession();
    	if (Util.isOnline(this) && session.isOpened()) {
    		//TODO: getfriends
    		new GetFriendScoreTask().execute(curPerson.getId());

    	}
    	else setEmptyListAdapter();
    }  
    
    private void displayFriendsScore(User[] friends) {
    	
    	scoreView = (ListView) findViewById(R.id.statsScores);
		FriendsAdapter fAdapter = new FriendsAdapter(MainActivity.this);
		for (int i = 0; i < friends.length; i++) {
			fAdapter.addItem(friends[i]);
		}
		
		if (scoreHeader != null) {
			if (scoreView == null) return;
			scoreView.removeHeaderView(scoreHeader);
		}
		if (scoreView.getHeaderViewsCount() < 1) {
			scoreHeader = (View)getLayoutInflater().inflate(R.layout.friend_score_header, null);
			setFriendScoreHeader();
			scoreView.addHeaderView(scoreHeader);
		}
		scoreView.setAdapter(fAdapter);
		
		setListViewHeightBasedOnChildren(scoreView);
		updateLayout();
    }
   
    private void getGamesToList() {
    	RestDataHandler dh = new RestDataHandler(this.getApplicationContext());
    	Game[] result = dh.getGamesFromDevice();
    	ListView gameList = (ListView)findViewById(R.id.gameListView);
		
		GameListAdapter arrayAdapter = new GameListAdapter(MainActivity.this);
		for(int i=0; i<result.length;i++) {
			arrayAdapter.addItem(result[i]);
		}
		gameList.setAdapter(arrayAdapter);
		
		setListViewHeightBasedOnChildren(gameList);
		updateLayout();		
    }
    
    private void createChart(PersonScore[] scores){
    	if (expList.isGroupExpanded(curGroupPosition)) {
    		LineChart lc = new LineChart(this);
    		expList.refreshDrawableState();
    		GraphicalView mChartView = lc.createChart(scores);
        	LinearLayout layout = (LinearLayout) expList.findViewById(R.id.chart); 
        	Display display = getWindowManager().getDefaultDisplay(); 
        	int w = display.getWidth();
	    	layout.removeAllViews();
	        layout.addView(mChartView, new LinearLayout.LayoutParams(w/5*3, 200)); 
    	}

    }
    
    private void updateLayout() {
    	RelativeLayout.LayoutParams rl;
    	if (playCtrl == GAME_LIST) rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, listHeight); 
    	else rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    	
    	rl.addRule(RelativeLayout.BELOW, R.id.personMain);
    	personDataViewSwitcher = (ViewSwitcher) findViewById(R.id.personDataViewSwitcher);
    	personDataViewSwitcher.setLayoutParams(rl);
    }
    
    private void setListViewHeightBasedOnChildren(ListView list) { 
        ListAdapter listAdapter = list.getAdapter();  
        if (listAdapter == null) {  
            return; 
        } 
 
        int totalHeight = 0; 
        for (int i = 0; i < listAdapter.getCount(); i++) { 
            View listItem = listAdapter.getView(i, null, list); 
            listItem.measure(0, 0); 
            totalHeight += listItem.getMeasuredHeight(); 
        } 

        ViewGroup.LayoutParams params = list.getLayoutParams(); 
        params.height = totalHeight + (list.getDividerHeight() * (listAdapter.getCount() - 1)); 
        listHeight = params.height;
        list.setLayoutParams(params); 
        list.requestLayout(); 
    }     
    
    // Show score result 
    public void startGame(int gameID) {
    	Bundle b = Util.setBundleObject(curPerson);

		Intent myIntent = new Intent(this, PostGameActivity.class);
		myIntent.putExtras(b);
		//myIntent.putExtra("categoryID", curCategory.getId());
		myIntent.putExtra("selectedGameID", gameID);
		
		startActivityForResult(myIntent, NEW_GAME);
    }
    
    //Update score on device after a game finished
    private void updateTotalScore() {		
		//For at update score af person (observer)
//		PersonListAdapter adapter = (PersonListAdapter)expList.getExpandableListAdapter();
//		curPerson.setScore(score);
//		adapter.setGroup(curGroupPosition, curPerson);
		
		//Update persons list, order by new persons place and update
		Person[] persons = dataHandler.getPersonsFromDevice(curCategory.getId());
		setExpandableListAdapter(persons);
	}
    
    private void setUserScoreHeader() {
    	TextView name = (TextView)scoreHeader.findViewById(R.id.header_name);
    	TextView score = (TextView)scoreHeader.findViewById(R.id.header_score);
    	TextView game = (TextView)scoreHeader.findViewById(R.id.header_game);
    	
    	name.setTypeface(Util.customFont(this), Typeface.BOLD);
    	score.setTypeface(Util.customFont(this), Typeface.BOLD);
    	game.setTypeface(Util.customFont(this));
    }
    
    private void setFriendScoreHeader() {
    	TextView name = (TextView)scoreHeader.findViewById(R.id.friend_header_name);
    	TextView score = (TextView)scoreHeader.findViewById(R.id.friend_header_score );
    	TextView image = (TextView)scoreHeader.findViewById(R.id.friend_header_image);
    	
    	name.setTypeface(Util.customFont(this), Typeface.BOLD);
    	score.setTypeface(Util.customFont(this), Typeface.BOLD);
    	image.setTypeface(Util.customFont(this));
    }

	public class GetLatestPlayerTask extends AsyncTask<Integer, Void, LatestPlayer[]>
    {    	
		protected void onPostExecute(LatestPlayer[] result)
    	{
			if (result!= null) {
				scoreView = (ListView) findViewById(R.id.statsScores);
				if (scoreView != null) {
					LatestPlayerAdapter lpAdapter = new LatestPlayerAdapter(MainActivity.this);
					for (int i = 0; i < result.length; i++) {
						lpAdapter.addItem(result[i]);
						
					}
					
					if (scoreHeader != null) scoreView.removeHeaderView(scoreHeader);
					if (scoreView.getHeaderViewsCount() < 1) {
						scoreHeader= (View)getLayoutInflater().inflate(R.layout.user_score_header, null);
						setUserScoreHeader();
						scoreView.addHeaderView(scoreHeader);
					}
					scoreView.setAdapter(lpAdapter);		
	
					setListViewHeightBasedOnChildren(scoreView);
					updateLayout();
					setDefaultSubList();
				}
			}
			
		}
    	
    	protected LatestPlayer[] doInBackground(Integer...params) {
			return RestDataHandler.getLatestPlayer(params[0]);
		}
    }
    
    private class GetHighScoreTask extends AsyncTask<Integer, Void, HighScore[]>
    {
    	protected void onPostExecute(HighScore[] result)
    	{
    		if (result != null) {
				scoreView = (ListView) findViewById(R.id.statsScores);
				HighScoreAdapter lpAdapter = new HighScoreAdapter(MainActivity.this);
				for (int i = 0; i < result.length; i++) {
					lpAdapter.addItem(result[i]);
					
				}
				
				if (scoreHeader != null) scoreView.removeHeaderView(scoreHeader);
				if (scoreView.getHeaderViewsCount() < 1) {
					scoreHeader = (View)getLayoutInflater().inflate(R.layout.user_score_header, null);
					setUserScoreHeader();
					scoreView.addHeaderView(scoreHeader);
				}
				scoreView.setAdapter(lpAdapter);
				
				setListViewHeightBasedOnChildren(scoreView);
				updateLayout();
    		}
		}
    	
    	
		@Override
		protected HighScore[] doInBackground(Integer... params) {
			return RestDataHandler.getHighScoreListByPerson(params[0]);
		}
    	
    }
    
    /**
	 * Getting friends score from database
	 */
	private class GetFriendScoreTask extends AsyncTask<Integer, Void, UserScore[]>
    {
    	protected void onPostExecute(UserScore[] result)
    	{
    		ArrayList<User> friends = FacebookFragment.friends;
    		if (result != null) {
	    		Map<Long, Long> map = new HashMap<Long, Long>();
	    		for (UserScore us : result) {	
	    			map.put(us.getUserID(), us.getScore());
	    		}
	    		
	    		ArrayList<User> friendsByPerson = new ArrayList<User>();
	    		for (int i = 0; i < friends.size(); i++) {
	    			long userId = friends.get(i).getId();
	    			if (map.containsKey(userId)) {
	    				friends.get(i).setScore(map.get(userId));
	    				friendsByPerson.add(friends.get(i));
	    			}
	    		}
	    		User[] arr = new User[friendsByPerson.size()];
	    		Arrays.sort(friendsByPerson.toArray(arr));
	    		displayFriendsScore(arr);
    		}
		}
    	
    	@Override
		protected UserScore[] doInBackground(Integer... params) {
			return RestDataHandler.getUserScoreByPerson(params[0]);
		}
    	
    }
    
    public class GetScoresTask extends AsyncTask<Integer, Void, PersonScore[]>
    {    	
		protected void onPostExecute(PersonScore[] result)
    	{
			if (result != null) {
				createChart(result);
			}
		}
    	
    	protected PersonScore[] doInBackground(Integer...params) {
			return RestDataHandler.getPersonScores(params[0]);
		}
    }
    
    private class GetBattlesTask extends AsyncTask<Void, Void, Battle[]>
    {
    	protected void onPostExecute(Battle[] result)
    	{
    		//Util.battles = result;
    		setBattleBanner(result);
		}
    	
		@Override
		protected Battle[] doInBackground(Void... params) {
			return RestDataHandler.getBattles(MainActivity.this);
		}
    	
    }

   
}